<template>
  <div class="app-container">
    <el-form ref="form" :model="form" size="mini" label-width="100px" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="title">人员工资</div>
          <el-row>
            <el-form-item label-width="0px">
              <el-button size="mini" type="primary" @click="handleAddRows('unitList', 1)">添加</el-button>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="4"><el-form-item label-width="80px" style="margin-bottom: 0px"  label="岗位名称" ></el-form-item></el-col>
            <el-col :span="4"><el-form-item label-width="80px" style="margin-bottom: 0px"  label="人员数量" ></el-form-item></el-col>
            <el-col :span="4"><el-form-item label-width="80px" style="margin-bottom: 0px"  label="工资基数" ></el-form-item></el-col>
            <el-col :span="4"><el-form-item label-width="80px" style="margin-bottom: 0px"  label="工资合计" ></el-form-item></el-col>
          </el-row>
          <el-row :gutter="10" v-for="(item, index) in form.unitList" :key="item.projectEstimateId">
            <el-col :span="4">
              <el-form-item label-width="0px" :prop="'unitList[' + index + '].businessId'"
                            :rules="{required: true, message: '请选择岗位', trigger: 'change'}">
                <el-select v-model="item.businessId" placeholder="请选择">
                  <el-option v-for="dict in dict.type.cld_project_post_estimate" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label-width="0px" :prop="'unitList[' + index + '].businessNumber'"
                            :rules="{required: true, message: '请输入人员数量', trigger: 'change'}">
                <el-input type="number" onkeyup="this.value = this.value.replace(/[^A-z0-9]/, '')"
                  v-model="item.businessNumber" :min="1" @input="handleChangeInput(item, 1)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label-width="0px" :prop="'unitList[' + index + '].businessUnitPrice'"
                            :rules="{required: true, message: '请输入工资基数', trigger: 'change'}">
                <el-input type="number" v-model="item.businessUnitPrice" :min="1" @input="handleChangeInput(item, 1)">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="businessUnitPriceTotal" label-width="0px">
                <el-input v-model="item.businessUnitPriceTotal" :disabled="true" :min="1">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button size="mini" type="danger" @click.prevent="handleDelete1(item, 'unitList', 1)">删除</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4"><el-form-item label-width="0px"></el-form-item></el-col>
            <el-col :span="4"><el-form-item label-width="0px"></el-form-item></el-col>
            <el-col :span="4"><el-form-item label-width="0px"></el-form-item></el-col>
            <el-col :span="4">
              <el-form-item label-width="0px">
                <el-input v-model="totalSalary" :disabled="true" :min="1">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="title">低值易耗</div>
          <el-row>
            <el-col :span="4">
              <el-form-item label-width="0px" prop="unitList1[0].businessUnitPrice">
                <el-input type="number" v-model="form.unitList1[0].businessUnitPrice">
                  <template slot="append">元/月</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="title">固定资产</div>
          <el-row>
            <el-form-item label-width="0px">
              <el-button size="mini" type="primary" @click="handleAddRows('unitList2', 3)">添加</el-button>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="4"><el-form-item label-width="80px" style="margin-bottom: 0px"  label="资产名称" ></el-form-item></el-col>
            <el-col :span="4"><el-form-item label-width="80px" style="margin-bottom: 0px"  label="资产数量" ></el-form-item></el-col>
            <el-col :span="4"><el-form-item label-width="80px" style="margin-bottom: 0px"  label="购置金额" ></el-form-item></el-col>
            <el-col :span="4"><el-form-item label-width="80px" style="margin-bottom: 0px"  label="金额合计" ></el-form-item></el-col>
          </el-row>
          <el-row :gutter="10" v-for="(item, index) in form.unitList2" :key="item.projectEstimateId">
            <el-col :span="4">
              <el-form-item label-width="0px" :prop="'unitList2[' + index + '].businessId'"
                            :rules="{required: true, message: '请选择资产', trigger: 'change'}">
                <el-select v-model="item.businessId" placeholder="请选择" @change="handleSelectAssetsChange(item)">
                  <el-option v-for="dict in assetsOptions" :key="dict.assetsId" :label="dict.assetsName" :value="dict.assetsId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :prop="'unitList2[' + index + '].businessNumber'" label-width="0px"
                            :rules="{required: true, message: '请输入资产数量', trigger: 'change'}">
                <el-input type="number" v-model="item.businessNumber" @input="handleChangeInput(item, 2)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="businessUnitPrice" label-width="0px">
                <el-input v-model="item.businessUnitPrice" :disabled="true"> <template
                    slot="append">元</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="businessUnitPriceTotal" label-width="0px">
                <el-input v-model="item.businessUnitPriceTotal" :disabled="true"> <template
                    slot="append">元</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button size="mini" type="danger" @click.prevent="handleDelete1(item, 'unitList2', 2)">删除</el-button>
            </el-col>
          </el-row>
          <div class="title">其他支出</div>
          <el-row>
            <el-form-item label-width="0px">
              <el-button size="mini" type="primary" @click="handleAddRows('unitList3', 4)">添加</el-button>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="4"><el-form-item label-width="80px" style="margin-bottom: 0px"  label="科目" ></el-form-item></el-col>
            <el-col :span="4"><el-form-item label-width="80px" style="margin-bottom: 0px"  label="计算方式" ></el-form-item></el-col>
          </el-row>
          <el-row :gutter="10" v-for="(item, index)  in form.unitList3" :key="item.projectEstimateId">
            <el-col :span="4">
              <el-form-item :prop="'unitList3[' + index + '].businessId'" label-width="0px" :rules="{required: true, message: '请选择科目', trigger: 'change'}">
                <el-cascader ref="cascader" v-model="item.businessId" :options="subjectOptions" :props="{
                    expandTrigger: 'hover',
                    value: 'subjectId',
                    label: 'subjectName',
                    checkStrictly: true,
                  }" clearable @change="handleTypeChange" :show-all-levels="false" placeholder="请选择科目"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :prop="'unitList3[' + index + '].calcType'" label-width="0px"
                            :rules="{required: true, message: '请选择计算方式', trigger: 'change'}">
                <el-select v-model="item.calcType" placeholder="请选择">
                  <el-option v-for="dict in chargeTypeOptions" :key="dict.value" :label="dict.label"
                    :value="parseInt(dict.value)"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :prop="'unitList3[' + index + '].businessUnitPrice'" label-width="0px">
                <el-input type="number" v-model="item.businessUnitPrice" @input="handleChangeInput(item, 3)">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" v-if="item.calcType == 1">
              <el-form-item prop="businessUnitPriceTotal" label-width="0px">
                <el-input v-model="item.businessUnitPriceTotal" disabled="disabled">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button size="mini" type="danger" @click.prevent="handleDelete1(item, 'unitList3', 3)">删除</el-button>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12">
          <div class="title">预估</div>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="预缴税费" prop="taxation">
                <el-input type="number" v-model="form.taxation" placeholder="请输入">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="年承包费用" prop="yearFee">
                <el-input type="number" v-model="form.yearFee" placeholder="请输入" @input="handleChangeInput(item, 4)">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="人均单价">
                <el-input type="number" v-model="perCapita" :disabled="true" >
                  <template slot="append">元/月</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-button size="mini" type="primary" @click="handleEstimate">预估</el-button>
          </el-row>
          <div class="title" style="margin-top: 10px;">预估结果</div>
          <el-row>
            <el-table v-loading="loading" :data="form.unitList4" size="mini" border>
              <h1>预估结果</h1>
              <el-table-column label="名称" align="center" prop="businessName" />
              <el-table-column label="单价/月" align="center" prop="businessUnitPriceMonth" />
              <el-table-column label="单价/年" align="center" prop="businessUnitPriceYear" />
            </el-table>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer-options">
      <el-button type="primary" @click="submitEstimateForm()">保存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>
<script>
import { addAssets, getAssetsList } from "@/api/cld/assets";
import { addEstimate, getEstimate } from "@/api/cld/estimate";
import { listSubject, } from "@/api/cld/subject";
import asc from "@/utils/asc";

export default {
  name: "profitEstimation",
  dicts: ['cld_project_post_estimate',
    'cld_project_other_expe',
    'cld_project_post'],

  data() {
    return {
      loading: false,
      form: {},
      assetsOptions: [],
      chargeTypeOptions: [{
        "label": "按人算",
        "value": 1
      }, {
        "label": "按总价",
        "value": 2
      }],
      // 人均单价
      perCapita: 0,
      // 工资合计
      totalSalary: 0,
      // 下拉科目
      subjectOptions: [],
    };
  },
  created() {
    this.reset();
    this.getListSubject();
    const projectId = this.$route.params && this.$route.params.projectId;
    if (projectId) {
      this.handleGetEstimate(projectId);
    }
    this.handleGetListAssets();
  },
  methods: {
    reset() {
      this.form = {
        projectId: this.$route.params.projectId,
        unitList: [],
        unitList1: [{ businessUnitPrice: null, estimateType: 2 }],
        unitList2: [],
        unitList3: [],
        unitList4: [],
        estimateList: []
      }
    },
    /** 获取科目列表 */
    getListSubject() {
      listSubject({
        subjectType: 2
      }).then((response) => {
        this.subjectOptions = this.handleTree(
          response.data,
          "subjectId",
          "subjectPid"
        );
      });
    },
    /** 科目选择 */
    handleTypeChange(e) {
      let nodesObj = this.$refs["cascader"].getCheckedNodes();
      if (nodesObj.length > 0) {
        let code = [];
        nodesObj[0].pathNodes.forEach((i) => {
          code.push(i.data.subjectNo);
        });
        // this.form.supplierTypeCode = code?.join(',');
      }
    },
    /** 加载计划设置 */
    handleGetEstimate(projectId) {
      getEstimate(projectId).then(res => {
        if (res.data) {
          this.form = res.data;
          //数据库String类型而option数字型,需parseInt()
          this.form.unitList2.filter(function (item) {
            item.businessId = parseInt(item.businessId);
          });
          //科目组装字符串
          this.form.unitList3.filter(function (item) {
            item.businessId = item.businessId?.split(",").map(Number);
          });
          // 合计工资
          this.totalSalary = this.form.unitList.reduce((sum, e) => sum + Number(e.businessUnitPriceTotal || 0), 0)
          // 计算人均单价
          this.perCapita = (this.form.yearFee / 12 / this.form.businessNumber).toFixed(2);
          this.handleEstimate()
        }
      })
    },
    /** 获取资产列表 */
    handleGetListAssets() {
      getAssetsList().then(res => {
        this.assetsOptions = res.data;
      })
    },
    /** 提交 */
    submitEstimateForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //科目组装字符串
          this.form.unitList3.filter(function (item) {
            item.businessId = item.businessId?.join(",");
          });
          //组装提交的数据
          this.form.estimateList = [];
          Array.prototype.push.apply(this.form.estimateList, this.form.unitList);
          Array.prototype.push.apply(this.form.estimateList, this.form.unitList1);
          Array.prototype.push.apply(this.form.estimateList, this.form.unitList2);
          Array.prototype.push.apply(this.form.estimateList, this.form.unitList3);
          addEstimate(this.form).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.cancel();
          });
        }
      });
    },
    /** 关闭计划设置 */
    cancel() {
      const obj = {path: "/cloudManage/project/project", name: "Project"};
      this.$tab.closeOpenPage(obj);
      this.$tab.refreshPage(obj);
    },
    /** 资产选择 */
    handleSelectAssetsChange(item) {
      let obj = this.assetsOptions.find(i => { return i.assetsId == item.businessId });
      item.businessUnitPrice = obj.bulMoney;
    },
    /** 计算 */
    handleChangeInput(row, type) {
      // 计算总人数
      let peopleTotal = 0;
      this.form.unitList.filter(function (item) {
        if (item.businessNumber) {
          peopleTotal += parseInt(item.businessNumber)
        }
      });
      // 人员工资集合修改
      if (type == 1) {
        row.businessUnitPriceTotal = parseInt(!row.businessNumber ? 0 : row.businessNumber) * parseFloat(!row.businessUnitPrice ? 0 : row.businessUnitPrice);
        // 修改其他支持中所有金额
        this.form.unitList3.filter(function (item) {
          if (item.calcType === 1) {
            if (peopleTotal > 0 && item.businessUnitPrice > 0) {
              item.businessUnitPriceTotal = peopleTotal * parseInt(item.businessUnitPrice);
            }
          }else{
            item.businessUnitPriceTotal += parseInt(item.businessUnitPrice);
          }
        });
        // 合计工资
        this.totalSalary = this.form.unitList.reduce((sum, e) => sum + Number(e.businessUnitPriceTotal || 0), 0)
      }
      // 固定资产
      if (type == 2) {
        row.businessUnitPriceTotal = parseInt(!row.businessNumber ? 0 : row.businessNumber) * parseFloat(!row.businessUnitPrice ? 0 : row.businessUnitPrice);
      }
      // 其他支出
      if (type == 3 ) {
        if(row.calcType === 1){
          row.businessUnitPriceTotal = parseFloat(!row.businessUnitPrice ? 0 : row.businessUnitPrice) * peopleTotal;
        }else{
          row.businessUnitPriceTotal = parseFloat(!row.businessUnitPrice ? 0 : row.businessUnitPrice) ;
        }
      }
      if (type == 1 || type == 4) {
        // 计算人均单价
        this.perCapita = (this.form.yearFee / 12 / peopleTotal).toFixed(2);
      }
    },
    /** 新增一行 */
    handleAddRows(fields, type) {
      this.form[fields].push({
        id: this.generateUUID(),
        estimateType: type
      })
    },
    /**
     * 人均单价：
     输入年承包费用 ÷ 12  = 带税总人均单价/月
     带税总人均单价/月 ÷ 人员数量 = 带税人均单价/月
     税费：
     总人均单价/月 * 税费 = 税费/月
     税费/月 * 12 = 税费/年
     利润：
     带税总人均单价/月 - 税费/月 = 去税总人均单价/月
     去税总人均单价/月 - 成本合计/月 = 利润/月
     利润/月 * 12 = 利润/年
     */
    handleEstimate() {
      this.form.unitList4.splice(0, this.form.unitList4.length);

      // 带税总人均单价/月 = 输入年承包费用 ÷ 12
      let monthFee = this.form.yearFee / 12;
      // 获取总人数
      let businessNumber = 0;
      this.form.unitList.filter(function (item) {
        if (item.businessNumber) {
          businessNumber = parseInt(businessNumber) + parseInt(item.businessNumber)
        }
      });
      //带税人均单价/月 = 带税总人均单价/月 ÷ 人员数量
      let monthFeeNew = monthFee / businessNumber

      // 税费/月 = 总人均单价/月 * 税费
      let taxationMonth = monthFee / (1 + (this.form.taxation / 100)) * (this.form.taxation / 100);
      // 税费/年 = 税费/月 * 12
      let taxationYear = taxationMonth * 12;
      console.log('税费/月->' + taxationMonth)
      console.log('税费/年->' + taxationYear)
      //计算利润
      //去税总人均单价/月 = 带税总人均单价/月 - 税费/月
      let notTaxationMonthFee = monthFee - taxationMonth;
      console.log('去税总人均单价/月->' + notTaxationMonthFee)
      // 去税总人均单价/月 - 成本合计/月 = 利润/月
      //获取成本
      let businessUnitPriceTotal = 0;
      this.form.unitList.filter(function (item) {
        businessUnitPriceTotal = parseFloat(businessUnitPriceTotal) + parseFloat(item.businessUnitPriceTotal)
      });
      let businessUnitPriceTotal1 = 0;
      this.form.unitList1.filter(function (item) {
        businessUnitPriceTotal1 = parseFloat(businessUnitPriceTotal1) + parseFloat(item.businessUnitPrice)
      });
      //
      let businessUnitPriceTotal2 = 0;
      this.form.unitList2.filter(function (item) {
        businessUnitPriceTotal2 = parseFloat(businessUnitPriceTotal2) + parseFloat(item.businessUnitPriceTotal)
      });
      //
      let businessUnitPriceTotal3 = 0;
      this.form.unitList3.filter(function (item) {
        businessUnitPriceTotal3 = parseFloat(businessUnitPriceTotal3) + parseFloat(item.businessUnitPriceTotal)
      });

      // 利润/月 = 去税总人均单价/月 - 成本合计/月
      // 单价月利润=年承包费用/12/(1+(预交税费/100)*(预交税费/100))-(人工工资+低值易耗+固定资产+其他支出)
      // 单价年利润=(年承包费用/12/(1+(预交税费/100)*(预交税费/100))-(人工工资+低值易耗+固定资产+其他支出))*12
      console.log(this.form)
      let profitMonth = monthFee - (monthFee /  (1 + (this.form.taxation / 100)) * (this.form.taxation / 100)) - (businessUnitPriceTotal + businessUnitPriceTotal1 + (businessUnitPriceTotal2/12) + businessUnitPriceTotal3);

      let profitYear =  profitMonth * 12;

      //估算类型(1人工工资2低值易耗3固定资产4其他支出)
      // this.form.unitList4=[];
      this.form.unitList4.push({ 'businessName': '人工工资', 'businessUnitPriceMonth': this.toMoney(businessUnitPriceTotal.toFixed(2)), 'businessUnitPriceYear': this.toMoney((businessUnitPriceTotal * 12).toFixed(2)) });
      this.form.unitList4.push({ 'businessName': '低值易耗', 'businessUnitPriceMonth': this.toMoney(businessUnitPriceTotal1.toFixed(2)), 'businessUnitPriceYear': this.toMoney((businessUnitPriceTotal1 * 12).toFixed(2)) });
      this.form.unitList4.push({ 'businessName': '固定资产', 'businessUnitPriceMonth': this.toMoney((businessUnitPriceTotal2 / 12).toFixed(2)), 'businessUnitPriceYear': this.toMoney((businessUnitPriceTotal2).toFixed(2)) });
      this.form.unitList4.push({ 'businessName': '其他支出', 'businessUnitPriceMonth': this.toMoney(businessUnitPriceTotal3.toFixed(2)), 'businessUnitPriceYear': this.toMoney((businessUnitPriceTotal3 * 12).toFixed(2)) });
      this.form.unitList4.push({ 'businessName': '成本合计', 'businessUnitPriceMonth': this.toMoney((businessUnitPriceTotal + businessUnitPriceTotal1 + (businessUnitPriceTotal2/12) + businessUnitPriceTotal3).toFixed(2)), 'businessUnitPriceYear': this.toMoney(((businessUnitPriceTotal + businessUnitPriceTotal1 + businessUnitPriceTotal2 + businessUnitPriceTotal3) * 12).toFixed(2)) });
      this.form.unitList4.push({ 'businessName': '预交税费', 'businessUnitPriceMonth': this.toMoney(taxationMonth.toFixed(2)), 'businessUnitPriceYear': this.toMoney((taxationYear).toFixed(2)) });
      this.form.unitList4.push({ 'businessName': '利润', 'businessUnitPriceMonth': this.toMoney(profitMonth.toFixed(2)), 'businessUnitPriceYear': this.toMoney((profitYear).toFixed(2)) });

      this.form.profitMonth = profitMonth.toFixed(2);
      this.form.profitYear = profitYear.toFixed(2);
    },
    /** 删除按钮操作 */
    handleDelete1(row, fields, type) {
      this.form[fields] = this.removeElement(this.form[fields], row);
    },
    removeElement(arr, value) {
      return arr.filter(function (item) {
        return item.id !== value.id;
      });
    },
    generateUUID() {
      const array = new Uint8Array(16);
      window.crypto.getRandomValues(array);
      let uuid = '';
      array.forEach((byte) => {
        uuid += byte.toString(16).padStart(2, '0');
      });
      return uuid;
    },
  }
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

.title {
  font-size: 26px;
  padding-left: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: left;
  color: black;
}
</style>
